package com.sanjiahantang.youjiaclient.jpush;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.orhanobut.logger.Logger;
import com.sanjiahantang.youjiaclient.base.CallBack;
import com.sanjiahantang.youjiaclient.config.ConfigValue;
import com.sanjiahantang.youjiaclient.config.SPConfig;
import com.sanjiahantang.youjiaclient.config.StaticValue;
import com.sanjiahantang.youjiaclient.http.BaseDelegate;
import com.sanjiahantang.youjiaclient.http.OkHttpClientManager;
import com.sanjiahantang.youjiaclient.module.common.beans.MessageBean;
import com.sanjiahantang.youjiaclient.module.common.beans.MessageNoticeCountBean;
import com.sanjiahantang.youjiaclient.module.common.beans.StringBean;
import com.sanjiahantang.youjiaclient.module.common.views.impl.MainActivity;
import com.sanjiahantang.youjiaclient.module.common.views.impl.SplashActivity;
import com.sanjiahantang.youjiaclient.module.common.views.impl.WebActivity;
import com.sanjiahantang.youjiaclient.module.goods.views.impl.GoodsDetailActivity;
import com.sanjiahantang.youjiaclient.module.match.views.impl.MatchActivity;
import com.sanjiahantang.youjiaclient.module.me.contract.models.impl.ContractModel;
import com.sanjiahantang.youjiaclient.module.me.order.beans.RequireOrderBean;
import com.sanjiahantang.youjiaclient.module.me.order.models.impl.OrderModel;
import com.sanjiahantang.youjiaclient.module.me.order.views.impl.OrderConfirmActivity;
import com.sanjiahantang.youjiaclient.module.me.require.beans.RequireListBean;
import com.sanjiahantang.youjiaclient.module.me.require.views.impl.RequireDetailActivity;
import com.sanjiahantang.youjiaclient.module.me.scheme.beans.MeCaseOBean;
import com.sanjiahantang.youjiaclient.module.me.scheme.views.impl.MeSchemeDetailActivity;
import com.sanjiahantang.youjiaclient.utils.SPUtils;
import com.squareup.okhttp.Request;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;

import static com.sanjiahantang.youjiaclient.config.StaticValue.INTENT_JPUSH_RECEIVER;
import static com.sanjiahantang.youjiaclient.config.StaticValue.KEY_JPUSH_RECEIVER;
import static com.sanjiahantang.youjiaclient.config.StaticValue.KEY_PARAM;

/**
 * 自定义接收器
 * <p>
 * 如果不定义这个 Receiver，则：
 * 1) 默认用户会打开主界面
 * 2) 接收不到自定义消息
 */
public class MyReceiver extends BroadcastReceiver implements StaticValue {
    private static final String TAG = "JIGUANG-MyReceiver";

    @Override
    public void onReceive(Context context, Intent intent) {
        try {
            Bundle bundle = intent.getExtras();
            Log.e(TAG, "[MyReceiver] onReceive - " + intent.getAction() + ", extras: " + printBundle(bundle));
            Logger.d(TAG, "[MyReceiver] onReceive - " + intent.getAction() + ", extras: " + printBundle(bundle));

            if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
                String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
                Log.e(TAG, "[MyReceiver] 接收Registration Id : " + regId);
                Logger.d(TAG, "[MyReceiver] 接收Registration Id : " + regId);
                //send the Registration Id to your server...

            } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
                Log.e(TAG, "[MyReceiver] 接收到推送下来的自定义消息: " + bundle.getString(JPushInterface.EXTRA_MESSAGE));
                Logger.d(TAG, "[MyReceiver] 接收到推送下来的自定义消息: " + bundle.getString(JPushInterface.EXTRA_MESSAGE));
                processCustomMessage(context, bundle);

            } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
                Log.e(TAG, "[MyReceiver] 接收到推送下来的通知");
                Logger.d(TAG, "[MyReceiver] 接收到推送下来的通知");
                int notifactionId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);

                Log.e(TAG, "[MyReceiver] 接收到推送下来的通知的ID: " + notifactionId);
                Logger.d(TAG, "[MyReceiver] 接收到推送下来的通知的ID: " + notifactionId);

            } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
                Log.e(TAG, "[MyReceiver] 用户点击打开了通知");
                Logger.d(TAG, "[MyReceiver] 用户点击打开了通知");

                String extra = bundle.getString(JPushInterface.EXTRA_EXTRA);
                Log.e("自定义字段sss", extra);
                try {
                    JSONObject jsonObject = new JSONObject(extra);

                    String type = jsonObject.getString("type");
                    if ("0".equals(type)) {
                        //打开web
                        Intent intent1 = new Intent(context, WebActivity.class);
                        intent1.putExtra("url", jsonObject.getString("pid"));
                        intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        context.startActivity(intent1);
                    } else if ("1".equals(type) || "5".equals(type) || "10".equals(type)) {
                        //获取表单详情页面数据
//                        Map<String,String> params=new HashMap<>();
//                        String token= SPUtils.get(context, SPConfig.KEY,"").toString();
                        int pid = Integer.valueOf(jsonObject.getString("pid"));
//                        Log.e("参数信息",token+"///"+pid);
//                        params.put("token",token);
//                        params.put("requireId",pid);
//                        getRequireDetail(context,params);

                        Intent i = new Intent(context, RequireDetailActivity.class);
                        i.putExtra(KEY_ID, pid);
                        i.putExtra(KEY_JPUSH_RECEIVER, INTENT_JPUSH_RECEIVER);
                        //i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        context.startActivity(i);
                    } else if ("2".equals(type)) {
                        String pid = jsonObject.getString("pid");
                        //打开方案页面
                        Intent i = new Intent(context, MeSchemeDetailActivity.class);
                        i.putExtra(KEY_ID, pid);
                        i.putExtra(KEY_JPUSH_RECEIVER, INTENT_JPUSH_RECEIVER);
                        //i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        context.startActivity(i);
                    } else if ("3".equals(type)) {
                        //获取表单详情页面数据
                        String pid = jsonObject.getString("pid");
                        Intent i = new Intent(context, GoodsDetailActivity.class);
                        i.putExtra("goodsId", Integer.valueOf(pid));
                        i.putExtra(KEY_JPUSH_RECEIVER, INTENT_JPUSH_RECEIVER);
                        //i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        context.startActivity(i);
                    } else if ("4".equals(type)) {
                        //获取表单详情页面数据
                        String pid = jsonObject.getString("pid");
                        Intent i = new Intent(context, MatchActivity.class);
                        i.putExtra(KEY_ID, Integer.valueOf(pid));
                        i.putExtra(KEY_JPUSH_RECEIVER, INTENT_JPUSH_RECEIVER);
                        //i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        context.startActivity(i);
                    } else if ("5".equals(type)) {
                        int pid = Integer.valueOf(jsonObject.getString("pid"));
                        goOrderConfirmPage(context, pid);
                    } else if ("6".equals(type)) {
                        int pid = Integer.valueOf(jsonObject.getString("pid"));
                        //打开首页工程
                        Intent i = new Intent(context, MainActivity.class);
                        i.putExtras(bundle);
                        i.putExtra(KEY_PAGE, 1);
                        ConfigValue.param = pid;
                        //i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        context.startActivity(i);
                    } else if ("13".equals(type)) {
                        //富文本
                        String pid = jsonObject.getString("pid");
                        loadRichText(context, pid);
                    } else {
                        //打开首页
                        Intent i = new Intent(context, MainActivity.class);
                        i.putExtras(bundle);
                        //i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        context.startActivity(i);
                    }
                } catch (Exception e) {
                    e.printStackTrace();

                    //打开首页
                    Intent i = new Intent(context, MainActivity.class);
                    i.putExtras(bundle);
                    //i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    context.startActivity(i);
                }


            } else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {
                Log.e(TAG, "[MyReceiver] 用户收到到RICH PUSH CALLBACK: " + bundle.getString(JPushInterface.EXTRA_EXTRA));
                Logger.d(TAG, "[MyReceiver] 用户收到到RICH PUSH CALLBACK: " + bundle.getString(JPushInterface.EXTRA_EXTRA));
                //在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码，比如打开新的Activity， 打开一个网页等..

            } else if (JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())) {
                boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);
                Log.e(TAG, "[MyReceiver]" + intent.getAction() + " connected state change to " + connected);
                Logger.w(TAG, "[MyReceiver]" + intent.getAction() + " connected state change to " + connected);
            } else {
                Log.e(TAG, "[MyReceiver] Unhandled intent - " + intent.getAction());
                Logger.d(TAG, "[MyReceiver] Unhandled intent - " + intent.getAction());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void loadRichText(final Context context, String pid) {
        Map<String, String> param = new HashMap<>();
        param.put("snId", pid);
        OkHttpClientManager.postAsyn(context, ConfigValue.API_URL + "/system/notice/findNoticeInfoById", param, new BaseDelegate.ResultCallback<StringBean>() {
            @Override
            public void onError(Request request, Object tag, Exception e) {
                Log.e("error", "error");
            }

            @Override
            public void onResponse(StringBean response, Object tag) {
                Log.e("返回结果", response.getCode() + "//");
                if (response != null && RESPONSE_CODE_SUC == response.getCode()) {
                    //打开表单详情页面
                    MessageBean.Data data = new Gson().fromJson(response.getData(), MessageBean.Data.class);
                    Intent intent = new Intent(context, WebActivity.class);
                    intent.putExtra(KEY_TYPE, WEB_TYPE_RICHTEXT);
                    intent.putExtra(KEY_NOTICE_CONTENT, data.getNoticeContent());
                    intent.putExtra(KEY_TITLE, data.getNoticeTitle());
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    context.startActivity(intent);
                }
            }
        });
    }

    private void goOrderConfirmPage(Context context, final int requireId) {
        Map<String, String> param = new HashMap<>();
        param.put(KEY_TOKEN, ConfigValue.DATA_KEY);
        param.put("requireId", String.valueOf(requireId));
        new ContractModel().findUserRequireByIdPhone(context, param, new CallBack<RequireListBean>() {
            @Override
            public void onSuccess(final RequireListBean requireListBean, Context context, Object tag) {
                if (requireListBean != null && requireListBean.getCode() == RESPONSE_CODE_SUC) {
                    Map<String, String> param = new HashMap<>();
                    param.put(KEY_TOKEN, ConfigValue.DATA_KEY);
                    param.put("requireId", String.valueOf(requireId));
                    new OrderModel().searchPriceDesignPhoneForRole(context, param, new CallBack<RequireOrderBean>() {
                        @Override
                        public void onSuccess(RequireOrderBean requireOrderBean, Context context, Object tag) {
                            if (requireOrderBean != null && requireOrderBean.getCode() == RESPONSE_CODE_SUC) {
                                context.startActivity(new Intent(context, OrderConfirmActivity.class)
                                        .putExtra("requireData", requireListBean.getItem())
                                        .putExtra(KEY_PARAM, requireOrderBean.getData())
                                );
                            }

                        }

                        @Override
                        public void onFailure(String message) {

                        }
                    });
                } else {
                }
            }

            @Override
            public void onFailure(String message) {

            }
        });
    }

    /**
     * 获取表单详情信息
     *
     * @param context
     * @param params
     */
    private void getRequireDetail(final Context context, Map<String, String> params) {
        OkHttpClientManager.postAsyn(context, ConfigValue.API_URL + "/user/phone/require/findUserRequireByIdPhone",
                params, new BaseDelegate.ResultCallback<RequireListBean>() {
                    @Override
                    public void onError(Request request, Object tag, Exception e) {
                        Log.e("error", "error");
                    }

                    @Override
                    public void onResponse(RequireListBean response, Object tag) {
                        Log.e("返回结果", response.getCode() + "//");
                        if (200 == response.getCode()) {
                            //打开表单详情页面
                            Intent i = new Intent(context, RequireDetailActivity.class);
                            i.putExtra(KEY_PARAM, response.getItem());
                            i.putExtra(KEY_JPUSH_RECEIVER, INTENT_JPUSH_RECEIVER);
                            //i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            context.startActivity(i);
                        }
                    }
                });
    }

    // 打印所有的 intent extra 数据
    private static String printBundle(Bundle bundle) {
        StringBuilder sb = new StringBuilder();
        for (String key : bundle.keySet()) {
            if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
            } else if (key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key));
            } else if (key.equals(JPushInterface.EXTRA_EXTRA)) {
                if (TextUtils.isEmpty(bundle.getString(JPushInterface.EXTRA_EXTRA))) {
                    Log.e(TAG, "This message has no Extra data");
                    Logger.i(TAG, "This message has no Extra data");
                    continue;
                }

                try {
                    JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
                    Iterator<String> it = json.keys();

                    while (it.hasNext()) {
                        String myKey = it.next();
                        sb.append("\nkey:" + key + ", value: [" +
                                myKey + " - " + json.optString(myKey) + "]");
                    }
                } catch (JSONException e) {
                    Log.e(TAG, "Get message extra JSON error!");
                    Logger.e(TAG, "Get message extra JSON error!");
                }

            } else {
                sb.append("\nkey:" + key + ", value:" + bundle.getString(key));
            }
        }
        return sb.toString();
    }

    //send msg to MainActivity
    private void processCustomMessage(Context context, Bundle bundle) {
        if (MainActivity.isForeground) {
            String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);
            String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
            Intent msgIntent = new Intent(MainActivity.MESSAGE_RECEIVED_ACTION);
            msgIntent.putExtra(MainActivity.KEY_MESSAGE, message);
            if (!JPushUtil.isEmpty(extras)) {
                try {
                    JSONObject extraJson = new JSONObject(extras);
                    if (extraJson.length() > 0) {
                        msgIntent.putExtra(MainActivity.KEY_EXTRAS, extras);
                    }
                } catch (JSONException e) {

                }

            }
            JPushBoardCastReceiver.getInstance(context).sendBroadcast(msgIntent);
        }
    }
}
